﻿using Microsoft.Owin;
using Newtonsoft.Json;
using Sustainalytics.Utils;
using Sustainalytics.Utils.WebApi.ErrorCodes;
using System;
using System.Net;
using System.Threading.Tasks;

namespace Sustainalytics.MostActiveReports.Service
{
    public class OwinExceptionMiddleware : OwinMiddleware
    {
        public OwinExceptionMiddleware(OwinMiddleware next)
            : base(next)
        {
        }

        public override async Task Invoke(IOwinContext context)
        {
            try
            {
                await this.Next.Invoke(context).ConfigureAwait(false);
            }
            catch (Exception ex)
            {

                CommonEventSource.Log.Exception(ex);

                this.HandleException(ex, context);
            }

        }

        private void HandleException(Exception ex, IOwinContext context)
        {
            var request = context.Request;

            //Build a model to represet the error for the client
            var errorDataModel = new { ErrorCode = WebAPIGeneralErrorCodes.UnhandledException };
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            context.Response.ReasonPhrase = "Internal Server Error";
            context.Response.ContentType = "application/json";
            context.Response.Write(JsonConvert.SerializeObject(errorDataModel));
        }
    }
}
